package com.web.cms.doc.provider;

import com.blue.core.dict.State;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.cms.doc.exception.ChannelException;
import com.web.cms.doc.facade.ChannelFacade;
import com.web.cms.doc.message.ChannelRequest;
import com.web.cms.doc.message.ChannelResponse;
import com.web.cms.doc.model.Channel;
import com.web.cms.doc.service.ChannelService;
import com.web.cms.doc.util.ChannelConvertor;
import com.web.cms.doc.util.ChannelUtil;
import com.web.core.async.redis.CacheRefreshSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component("cmsChannelProvider")
public class ChannelProvider implements ChannelFacade
{
	@Autowired
	private ChannelService channelService;
	@Autowired
	private ChannelUtil channelUtil;
	@Resource
	private CacheRefreshSender cacheRefreshSender;
	
	public ChannelProvider()
	{
	}

	@Override
	public ChannelResponse add(ChannelRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Channel channel = ChannelConvertor.toChannel(request);
		channel = channelService.save(channel);
		cacheRefreshSender.send(CacheRefreshSender.DOC_CHANNEL_CACHE, channel.getId());
		ChannelResponse response = ChannelConvertor.toResponse(channel);
		return response;
	}

	@Override
	public ChannelResponse update(ChannelRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Channel channel = ChannelConvertor.toChannel(request);
		channel = channelService.save(channel);
		cacheRefreshSender.send(CacheRefreshSender.DOC_CHANNEL_CACHE, channel.getId());
		ChannelResponse response = ChannelConvertor.toResponse(channel);
		return response;
	}

	@Override
	public ChannelResponse get(Integer id)
	{
		if (id == null)
			throw new ChannelException("栏目ID不能为空");
			
		Channel channel = channelUtil.get(id);
		ChannelResponse response = ChannelConvertor.toResponse(channel);
		return response;
	}

	@Override
	public List<ChannelResponse> list(Integer webId, Integer parentId, State state)
	{
		List<Channel> list = channelUtil.listByWebAndParent(webId, parentId, state);
		List<ChannelResponse> responseList = ChannelConvertor.toResponse(list);
		return responseList;
	}

	@Override
	public Map<String, List<ChannelResponse>> listTree(Integer webId, State state)
	{
		Map<Integer, List<Channel>> map = channelUtil.listByWeb(webId, state);
		Map<String, List<ChannelResponse>> responseMap = ChannelConvertor.toTree(map);
		return responseMap;
	}
	
	@Override
	public void refresh()
	{
		cacheRefreshSender.send(CacheRefreshSender.DOC_CHANNEL_CACHE);
	}
	
}
